﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;

namespace WpfApplication1
{
	/// <summary>
	/// Interaction logic for GameMessageBox.xaml
	/// </summary>
	public partial class GameAdminLobby : Window
	{
		public delegate void RequestAdminQuery(String message);
		public RequestAdminQuery requestAdminQuery;

		private bool recreateGame;
		private bool newGame;
		private static String guid;
		private static string gamePath = @"..\..\..\WindowsGame1\WindowsGame1\bin\x86\Debug\WindowsGame1.exe";
		private static string serverPath = @"..\..\..\XnaGameServer\bin\Debug\XnaGameServer.exe";
		private String settings;

		Lobby.RequestQuery requestLobbyTrigger;

		public GameAdminLobby(Lobby.RequestQuery rQ, String gameid)
		{
			requestLobbyTrigger = rQ;
			requestAdminQuery = new RequestAdminQuery(this.addAdminMessageDelegate);
			HTTP.registerGameQuery(requestAdminQuery);
			recreateGame = true;
			newGame = true;
			guid = gameid;
			InitializeComponent();
			Closing += GameAdminLobby_Closing;
		}

		void GameAdminLobby_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if(!this.newGame)
				HTTP.sendToServer("type=game&subtype=remove&gameid="+guid);
			requestLobbyTrigger.Invoke("enableCreateGame");
			
		}

		public void KickUser_GameLobby_Click(object sender, RoutedEventArgs e)
		{
			HTTP.sendToServer("type=game&subtype=banuser&username="+playerGameList.SelectedValue.ToString()+"&gameid="+guid);
		}

		public void addAdminMessageDelegate(String message)
		{
			String[] msg = message.Split(new string[] { "query?" }, StringSplitOptions.None)[1].Split('&');
			string type = "";
			String messageData = "";
			foreach (String m in msg)
			{
				if (type != "")
				{
					messageData = m.Split('=')[1];
					if (type == "add")
					{
						playerGameList.Dispatcher.BeginInvoke(new Action(delegate()
						{
							playerGameList.Items.Add(messageData);
						}));
					}
					if (type == "remove")
					{
						playerGameList.Dispatcher.BeginInvoke(new Action(delegate()
						{
							playerGameList.Items.RemoveAt(playerGameList.Items.IndexOf(messageData));
						}));
					}
				}

				if (m == "type=add")
				{
					type = "add";
				}
				if (m == "type=remove")
				{
					type = "remove";
				}
			}
		}

		private void StartGameButton_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (recreateGame == false || newGame)
				{
					Convert.ToInt32(SeedTextBox.Text);
					Convert.ToInt32(LivesTextBox.Text);
					if (GameNameTextBox.Text != "" && GameNameTextBox.Text.Split(' ').Length != 0 && LivesTextBox.Text != "" && SeedTextBox.Text != "")
					{
						String startgame = StartGameButton.Content.ToString();
						if (startgame != "Start Game")
						{
							if (HTTP.GETfromServer("type=game&subtype=add&gamename=" + GameNameTextBox.Text + "&ipaddress=" + HTTP.URL + "&username=" + Lobby.getUsername() + "&settings=" + getSettings() + "&id=" + guid) != "success")
							{
								MessageBox.Show("Cannot start game");
							}
							else
							{
								recreateGame = false;
								newGame = false;
								GameNameTextBox.IsReadOnly = true;
								StartGameButton.Content = "Start Game";
								String setting = getSettings();
								playerGameList.Items.Add(Lobby.getUsername());
								settings = setting;
							}

						}
						else
						{
							if (HTTP.GETfromServer("", "type=ingame&subtype=startgame&gameid=" + guid) == "success")
							{
                                Console.WriteLine(1);
                                for (int i = 5; i > 0; i--)
                                {
                                    StartGameButton.Content = "Starts in: " + i;
                                    Thread.Sleep(1000);
                                }
                                


								System.Diagnostics.Process server = new System.Diagnostics.Process();
								server.StartInfo.FileName = serverPath;
								server.Start();

								var ip = HTTP.LocalIPAddress();
								System.Diagnostics.Process game = new System.Diagnostics.Process();
								game.StartInfo.FileName = gamePath;
								game.StartInfo.Arguments = SeedTextBox.Text + " " + LivesTextBox.Text + " " + ip + " " + ip;
								game.Start();
								game.WaitForExit();
								//RUN GAME
							}
						}
					}
				}
				else
				{
					if (HTTP.GETfromServer("", "type=ingame&subtype=changeoptions&gameid=" + guid + "&settings=" + getSettings()) != "success")
					{
						settings = getSettings();
						MessageBox.Show("Options weren't able to be changed.");
					}
				}
			}
			catch
			{ }
		}

		private string getSettings()
		{
			String setting;
			setting = gamesizeComboBox.SelectedIndex.ToString();
			setting += "-" + LivesTextBox.Text + "-" + SeedTextBox.Text;
			return setting;
		}

		private void ResetButton_Click(object sender, RoutedEventArgs e)
		{
			if (settings != null)
			{
				String[] sett = settings.Split('-');
				gamesizeComboBox.SelectedIndex = Convert.ToInt32(sett[0]);
				LivesTextBox.Text = sett[1];
				SeedTextBox.Text = sett[2];
				recreateGame = false;

				StartGameButton.Content = "Start Game";
			}
		}

		private void nullifyStartup()
		{
			if (recreateGame == false)
			{
				StartGameButton.Content = "Reconfigure Game";
				recreateGame = true;
			}
		}

		private void LivesTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
		{
			nullifyStartup();
		}

		private void GameTimeTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
		{
			nullifyStartup();
		}

		private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
		{
			nullifyStartup();
		}

		private void ComboBox_Loaded_1(object sender, RoutedEventArgs e)
		{
			List<string> data = new List<string>();
			data.Add("5 v 5");
			data.Add("10 v 10");
			data.Add("15 v 15");
			data.Add("Free for all");

			// ... Get the ComboBox reference.
			var comboBox = sender as ComboBox;

			// ... Assign the ItemsSource to the List.
			comboBox.ItemsSource = data;

			// ... Make the first item selected.
			comboBox.SelectedIndex = 0;
		}
	}
}
